import { GameComponent } from "@sapi-game/gameComponent";
import { Game } from "@sapi-game/main";
import { Duration, Vector3Utils } from "@sapi-game/utils";
import { BlockedMainState } from "../states/mainState";

export class BlockedPortalCleaner extends GameComponent<BlockedMainState> {
    readonly PORTAL_OFFSETS = [
        { x: 1, y: 0, z: 0 },
        { x: -1, y: 0, z: 0 },
        { x: 0, y: 0, z: 1 },
        { x: 0, y: 0, z: -1 },
    ];

    override onAttach(): void {
        this.subscribe(
            Game.events.interval,
            () => this.clearPortal(),
            new Duration(40)
        );
    }

    clearPortal() {
        for (const p of this.context.groupSet.getAllValidPlayers()) {
            if (p.live <= 0) continue;

            const player = p.player;
            const dim = player.dimension;
            const loc = player.location;

            for (const offset of this.PORTAL_OFFSETS) {
                try {
                    const pos = Vector3Utils.add(loc, offset);
                    const block = dim.getBlock(pos);
                    if (block?.typeId === "minecraft:portal") {
                        block.setType("air");
                    }
                } catch (err) {}
            }
        }
    }
}
